package com.nx.platform.es.bean.modle.param;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.nx.platform.es.bean.dto.RequestContext;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.List;
import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class ParamField {

    private final ParamFieldType type;
    private final ImmutableMap<String, ?> config;

    private ParamField(ParamFieldType type, ImmutableMap<String, ?> config) {
        this.type = type;
        this.config = config;
    }

    public static ParamField create(Map<?, ?> settings) {
        String type = MoreMaps.getString(settings, "type");
        Preconditions.checkState(!Strings.isNullOrEmpty(type), "type not found");
        ParamFieldType fieldType = ParamFieldType.valueOf(type);
        ImmutableMap<String, ?> config = fieldType.getParser().parse(settings);
        return new ParamField(fieldType, config);
    }

    public void handle(RequestContext context,
                       Table<String, StatementOperator, List<String>> queryTable,
                       Table<String, StatementOperator, List<String>> paramsTable,
                       Map<String, Object> paramsMap) {
        type.getHandler().handle(context, config, queryTable, paramsTable, paramsMap);
    }

    public ParamFieldType getType() {
        return type;
    }

    public ImmutableMap<String, ?> getConfig() {
        return config;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(config);
        return builder.toString();
    }

}
